import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  HttpStatus,
  HttpCode,
  BadRequestException,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { CustomerQuotationService } from './customer-quotation.service';
import { UploadPicturesService } from '../common/upload/upload-pictures.service';
import { OssUtilService } from '../common/upload/oss-util.service';
import { CreateCustomerQuotationDto } from './dto/create-customer-quotation.dto';
import { UpdateCustomerQuotationDto } from './dto/update-customer-quotation.dto';
import { v4 as uuidv4 } from 'uuid';

@Controller('customer-quotation')
export class CustomerQuotationController {
  constructor(
    private readonly customerQuotationService: CustomerQuotationService,
    private readonly uploadPicturesService: UploadPicturesService,
    private readonly ossUtilService: OssUtilService,
  ) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  async create(@Body() createCustomerQuotationDto: CreateCustomerQuotationDto) {
    console.log('=== 客户报价创建调试 ===');
    console.log('创建DTO:', createCustomerQuotationDto);
    
    // 如果有图片数据，先处理图片上传
    if (createCustomerQuotationDto.picture && createCustomerQuotationDto.picture.startsWith('blob:')) {
      console.log('检测到blob URL，需要处理图片上传');
      // 这里可以添加图片处理逻辑
      // 例如：将blob URL转换为OSS URL并保存图片记录
    }
    
    const result = await this.customerQuotationService.create(createCustomerQuotationDto);
    return {
      success: true,
      data: result,
      message: '客户报价创建成功'
    };
  }



  @Get()
  async findAll(
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '50',
  ) {
    const pageNum = Math.max(1, parseInt(page) || 1);
    const limitNum = Math.min(1000, Math.max(1, parseInt(limit) || 50));
    const result = await this.customerQuotationService.findAll(pageNum, limitNum);
    return {
      success: true,
      data: result.data,
      total: result.total,
      page: result.page,
      limit: result.limit,
      message: '获取客户报价列表成功'
    };
  }

  @Get('search')
  async search(
    @Query('keyword') keyword: string,
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '50',
  ) {
    if (!keyword || keyword.trim() === '') {
      throw new BadRequestException('搜索关键词不能为空');
    }
    const pageNum = Math.max(1, parseInt(page) || 1);
    const limitNum = Math.min(1000, Math.max(1, parseInt(limit) || 50));
    const result = await this.customerQuotationService.search(keyword, pageNum, limitNum);
    return {
      success: true,
      data: result.data,
      total: result.total,
      page: result.page,
      limit: result.limit,
      message: '搜索客户报价成功'
    };
  }





  @Get('detail/:quoteid')
  async findByQuoteid(@Param('quoteid') quoteid: string) {
    const result = await this.customerQuotationService.findByQuoteid(quoteid);
    return {
      success: true,
      data: result,
      message: '获取客户报价详情成功'
    };
  }

  @Get('detail-with-replies/:quoteid')
  async findByQuoteidWithReplies(@Param('quoteid') quoteid: string) {
    const result = await this.customerQuotationService.findByQuoteidWithReplies(quoteid);
    return {
      success: true,
      data: result,
      message: '获取客户报价详情及回复成功'
    };
  }

  @Patch(':quoteid')
  async update(
    @Param('quoteid') quoteid: string,
    @Body() updateCustomerQuotationDto: UpdateCustomerQuotationDto,
  ) {
    const result = await this.customerQuotationService.update(quoteid, updateCustomerQuotationDto);
    return {
      success: true,
      data: result,
      message: '客户报价更新成功'
    };
  }

  @Delete(':quoteid')
  @HttpCode(HttpStatus.OK)
  async remove(@Param('quoteid') quoteid: string) {
    await this.customerQuotationService.remove(quoteid);
    return {
      success: true,
      message: '客户报价删除成功'
    };
  }

  // 上传客户报价图片接口
  @Post('uploadimg')
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(@UploadedFile() file: Express.Multer.File) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const fileName = file.originalname;
    const suffixName = fileName.substring(fileName.lastIndexOf('.'));
    const newFileName = uuidv4() + suffixName;

    try {
      const result = await this.ossUtilService.uploadFile(
        'hasmarket',
        'customerquote',
        newFileName,
        file.buffer,
      );

      return {
        success: true,
        data: {
          url: result.url,
          name: newFileName,
          originalName: fileName,
          size: file.size,
          mimeType: file.mimetype,
        },
        message: '上传成功',
      };
    } catch (error) {
      throw new BadRequestException('上传失败');
    }
  }

  // 添加图片记录到数据库
  @Post('addimageitem')
  async addImageItem(@Body() imageData: any) {
    try {
      console.log('=== addImageItem 调试 ===');
      console.log('接收到的 imageData:', imageData);
      console.log('imageData.imageUrl:', imageData.imageUrl);
      console.log('imageData.url:', imageData.url);
      
      // 兼容两种字段名
      const imageUrl = imageData.imageUrl || imageData.url;
      
      if (!imageUrl) {
        throw new BadRequestException('缺少 imageUrl 字段');
      }
      
      const createData = {
        serviceId: imageData.serviceId,
        name: imageData.name,
        imageUrl: imageUrl,
        suffix: imageData.suffix || '.jpg',
      };
      
      console.log('准备创建的数据:', createData);
      
      const result = await this.uploadPicturesService.create(createData);

      console.log('创建结果:', result);

      return {
        success: true,
        data: result,
        message: '图片记录添加成功',
      };
    } catch (error) {
      console.error('addImageItem 错误:', error);
      throw new BadRequestException('图片记录添加失败: ' + error.message);
    }
  }

  // 删除图片
  @Post('deleteimg')
  async deleteImage(@Body() deleteData: { filename: string; serviceid: string }) {
    try {
      // 从OSS删除文件
      await this.ossUtilService.deleteFile('hasmarket', 'customerquote', deleteData.filename);
      
      // 从数据库软删除记录
      await this.uploadPicturesService.softDeleteByServiceId(deleteData.serviceid);

      return {
        success: true,
        message: '图片删除成功',
      };
    } catch (error) {
      throw new BadRequestException('图片删除失败: ' + error.message);
    }
  }
} 